import 'package:flutter/foundation.dart';
import '../services/storage_service.dart';
import '../services/log_service.dart';

class SettingsProvider with ChangeNotifier {
  final StorageService _storageService = StorageService();

  bool _autoConnect = false;
  bool _systemProxy = true;
  bool _autoUpdate = false;
  int _updateInterval = 24;
  bool _mux = true;
  bool _allowInsecure = false;
  String _theme = 'system'; // light, dark, system
  String _language = 'zh'; // en, zh
  bool _showTrafficInTitle = true;
  bool _enableNotifications = true;
  bool _soundEnabled = true;
  bool _vibrationEnabled = true;
  String _proxyMode = 'global'; // global, rule, direct
  int _tcpConcurrency = 8;
  bool _enableSniffing = true;
  bool _enableMitm = false;
  String _dnsServer = '8.8.8.8';
  bool _enableIPv6 = false;
  int _connectionTimeout = 30;
  LogLevel _logLevel = LogLevel.warning; // 日志显示级别
  bool _showServerIndex = false; // 显示服务器序号

  // Getters
  bool get autoConnect => _autoConnect;
  bool get systemProxy => _systemProxy;
  bool get autoUpdate => _autoUpdate;
  int get updateInterval => _updateInterval;
  bool get mux => _mux;
  bool get allowInsecure => _allowInsecure;
  String get theme => _theme;
  String get language => _language;
  bool get showTrafficInTitle => _showTrafficInTitle;
  bool get enableNotifications => _enableNotifications;
  bool get soundEnabled => _soundEnabled;
  bool get vibrationEnabled => _vibrationEnabled;
  String get proxyMode => _proxyMode;
  int get tcpConcurrency => _tcpConcurrency;
  bool get enableSniffing => _enableSniffing;
  bool get enableMitm => _enableMitm;
  String get dnsServer => _dnsServer;
  bool get enableIPv6 => _enableIPv6;
  int get connectionTimeout => _connectionTimeout;
  LogLevel get logLevel => _logLevel;
  bool get showServerIndex => _showServerIndex;

  SettingsProvider() {
    _loadSettings();
  }

  Future<void> _loadSettings() async {
    final settings = await _storageService.loadSettings();
    _autoConnect = settings['autoConnect'] ?? false;
    _systemProxy = settings['systemProxy'] ?? true;
    _autoUpdate = settings['autoUpdate'] ?? false;
    _updateInterval = settings['updateInterval'] ?? 24;
    _mux = settings['mux'] ?? true;
    _allowInsecure = settings['allowInsecure'] ?? false;
    _theme = settings['theme'] ?? 'system';
    _language = settings['language'] ?? 'zh';
    _showTrafficInTitle = settings['showTrafficInTitle'] ?? true;
    _enableNotifications = settings['enableNotifications'] ?? true;
    _soundEnabled = settings['soundEnabled'] ?? true;
    _vibrationEnabled = settings['vibrationEnabled'] ?? true;
    _proxyMode = settings['proxyMode'] ?? 'global';
    _tcpConcurrency = settings['tcpConcurrency'] ?? 8;
    _enableSniffing = settings['enableSniffing'] ?? true;
    _enableMitm = settings['enableMitm'] ?? false;
    _dnsServer = settings['dnsServer'] ?? '8.8.8.8';
    _enableIPv6 = settings['enableIPv6'] ?? false;
    _connectionTimeout = settings['connectionTimeout'] ?? 30;
    
    // 从存储中读取日志级别（兼容旧版本的整数值）
    final logLevelValue = settings['logLevel'];
    if (logLevelValue is String) {
      _logLevel = LogLevel.values.firstWhere(
        (e) => e.name == logLevelValue,
        orElse: () => LogLevel.warning,
      );
    } else if (logLevelValue is int) {
      // 兼容旧版本：0=none, 1=error, 2=warning, 3=info, 4=debug
      switch (logLevelValue) {
        case 0:
        case 1:
          _logLevel = LogLevel.error;
          break;
        case 2:
          _logLevel = LogLevel.warning;
          break;
        case 3:
          _logLevel = LogLevel.info;
          break;
        case 4:
          _logLevel = LogLevel.debug;
          break;
        default:
          _logLevel = LogLevel.warning;
      }
    } else {
      _logLevel = LogLevel.warning;
    }
    
    _showServerIndex = settings['showServerIndex'] ?? false;
    notifyListeners();
  }

  Future<void> _saveSettings() async {
    await _storageService.saveSettings({
      'autoConnect': _autoConnect,
      'systemProxy': _systemProxy,
      'autoUpdate': _autoUpdate,
      'updateInterval': _updateInterval,
      'mux': _mux,
      'allowInsecure': _allowInsecure,
      'theme': _theme,
      'language': _language,
      'showTrafficInTitle': _showTrafficInTitle,
      'enableNotifications': _enableNotifications,
      'soundEnabled': _soundEnabled,
      'vibrationEnabled': _vibrationEnabled,
      'proxyMode': _proxyMode,
      'tcpConcurrency': _tcpConcurrency,
      'enableSniffing': _enableSniffing,
      'enableMitm': _enableMitm,
      'dnsServer': _dnsServer,
      'enableIPv6': _enableIPv6,
      'connectionTimeout': _connectionTimeout,
      'logLevel': _logLevel.name, // 保存为字符串
      'showServerIndex': _showServerIndex,
    });
  }

  Future<void> setAutoConnect(bool value) async {
    _autoConnect = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setSystemProxy(bool value) async {
    _systemProxy = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setAutoUpdate(bool value) async {
    _autoUpdate = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setUpdateInterval(int value) async {
    _updateInterval = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setMux(bool value) async {
    _mux = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setAllowInsecure(bool value) async {
    _allowInsecure = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setTheme(String value) async {
    _theme = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setLanguage(String value) async {
    _language = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setShowTrafficInTitle(bool value) async {
    _showTrafficInTitle = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setEnableNotifications(bool value) async {
    _enableNotifications = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setSoundEnabled(bool value) async {
    _soundEnabled = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setVibrationEnabled(bool value) async {
    _vibrationEnabled = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setProxyMode(String value) async {
    _proxyMode = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setTcpConcurrency(int value) async {
    _tcpConcurrency = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setEnableSniffing(bool value) async {
    _enableSniffing = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setEnableMitm(bool value) async {
    _enableMitm = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setDnsServer(String value) async {
    _dnsServer = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setEnableIPv6(bool value) async {
    _enableIPv6 = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setConnectionTimeout(int value) async {
    _connectionTimeout = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setLogLevel(LogLevel value) async {
    _logLevel = value;
    await _saveSettings();
    notifyListeners();
  }

  Future<void> setShowServerIndex(bool value) async {
    _showServerIndex = value;
    await _saveSettings();
    notifyListeners();
  }
}
